#include "head.h"

/* Usage:  客户端*/

int do_cd(client_status_t *client){
    //
    char path[200] = {0};
    for(int i=0; i<strlen(client->runtime_cmd); i++){
        path[i] = client->runtime_cmd[i+3];
    }

    self_defined_pro_t *protect = (self_defined_pro_t *)calloc(1,sizeof(self_defined_pro_t));

    //第一种cd .的情况，直接回到当前目录下
    if(!strcmp(path, ".")){
        return 0;
    }
    //第二种情况，调用家目录的文件的路径，然后转到家目录下
    if(path == NULL || !strcmp(path, "~")){
        memcpy(client->path, "/", 1);
        return 0;
    }
    if(!strcmp(path, "/")){
        memcpy(client->path, "/", 1);
        return 0;
    }
    if(!strcmp(path, "..")){
        if(strlen(client->path ) == 1){
            return 0;
        } 

        for(int i=strlen(client->path)-1; i>0; i--){
            if(client->path[i] != '/'){
                client->path[i] = 0;
            } else{
                break;
            }
        }

        if(strlen(client->path ) == 1){
            return 0;
        }else{
            client->path[strlen(client->path)-1] =0;
        } 

        return 0;
    }

    //直接传给服务端
    memset(protect, 0, sizeof(self_defined_pro_t));
    protect->cmd = cd;

    strcat(protect->message,"username=");
    strcat(protect->message,client->user);
    strcat(protect->message,"&");
    strcat(protect->message,"path=");
    strcat(protect->message,client->path);
    strcat(protect->message,"&");
    strcat(protect->message,"cd=");
    strcat(protect->message,path);

    protect->message_len = strlen(protect->message);
    protect->para_num = 3;

    send(client->socket_fd, protect, sizeof(self_defined_pro_t), MSG_NOSIGNAL);

    self_defined_pro_t *mes=(self_defined_pro_t *)calloc(1,sizeof(self_defined_pro_t));
    recv(client->socket_fd, mes, sizeof(self_defined_pro_t), MSG_WAITALL);

    if(mes->cmd == 0 && mes->para_num == 2){

        if(strlen(client->path) != 1){
            strcat(client->path, "/");
        }
        strcat(client->path, path);
        return 0;
    }else{
        return -1;
    }
    free(mes);
    free(protect);
    return 0;
}


